package com.hatricks.is.base.mysql;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.util.ClassLoaderUtil;
import cn.hutool.core.util.RandomUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.concurrent.TimeUnit;

/**
 * @author: hatricks
 * @description: 使用原生JDBC插入数据库10万条, 实测大概2s
 */
public class Insert {

    private static final String URL = "jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true&serverTimezone=GMT";
    private static final String USER = "root";
    private static final String PASSWORD = "root";

    public static void main(String[] args) {
        StopWatch stopWatch = new StopWatch("插入数据");
        stopWatch.start("插入数据");
//        100 70000
        String sql = "INSERT INTO sc(sc_id,s_id,c_id,score) VALUES(?,?,?,?)";
        ClassLoaderUtil.loadClass("com.mysql.cj.jdbc.Driver");
        try (Connection connect = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement pst = connect.prepareStatement(sql);) {
            connect.setAutoCommit(Boolean.FALSE);
            for (int i = 1; i <= 70_0000; i++) {
                pst.setInt(1, i);
                pst.setInt(2, RandomUtil.randomInt(1, 700000));
                pst.setInt(3, RandomUtil.randomInt(1, 100));
                pst.setInt(4, RandomUtil.randomInt(1, 100));
                pst.addBatch();
            }
            pst.executeBatch();
            connect.commit();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        stopWatch.stop();
        System.out.println(stopWatch.prettyPrint(TimeUnit.SECONDS));
    }
}
